package com.sie.zhq.module;

import android.util.Log;

import com.sie.zhq.constconfig.ConstDefine;
import com.sie.zhq.tool.ByteTool;
import com.sie.zhq.tool.Crc16;

import java.io.IOException;

/**
 * Created by zhq on 2017/7/10.
 */

public class SIOModule extends SerialPortModule {

    public final static String TAG = "SIOModule";
    private static SIOModule ourInstance = new SIOModule();


    public static SIOModule getInstance() {
        return ourInstance;
    }

    private String serialDev = ConstDefine.CTRL_PORT;
    private int baudRate = 9600;
    protected boolean isOpen = false;

    public SIOModule(){

        boolean init = initSerialPort(serialDev,baudRate);
        Log.e("SIOModule init",init+"---");
    }

    public int control(byte address,byte ctrl,byte road,byte openOrClose){
        byte[] cmd = new byte[8];
        cmd[0] = address;
        cmd[1] = ctrl;
        cmd[2] = 0x00;
        cmd[3] = road;
        cmd[4] = openOrClose;
        cmd[5] = 0x00;

        int num = Crc16.calcCrc16(cmd,0,6);
        byte[] crc = ByteTool.int2Bytes(num);
        cmd[6] = crc[1];
        cmd[7] = crc[0];
        Log.e("cmd",ByteTool.byte2hex(cmd));
        this.writeFlush(cmd, cmd.length);

        int res = 0;
        byte[] result = new byte[8];
        try {
            res = receiveBytes(result,8,1000);
            Log.e("result",ByteTool.byte2hex(result));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return res;

    }





}
